﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Hosting;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SignalRvideo
{
    public class BroadcastService: BackgroundService
    {
        private readonly IHubContext<WebSignalHub> _hubContext;

        public BroadcastService(IHubContext<WebSignalHub> hubContext)
        {
            _hubContext = hubContext;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            return Task.Factory.StartNew(async () => { await Broadcast(stoppingToken); }, TaskCreationOptions.LongRunning);
        }

        //读取内置摄像头
        private async Task Broadcast(CancellationToken stoppingToken)
        {
            VideoCapture capture = new VideoCapture();
            string rtspUrl = @"rtsp://192.168.240.1:23333/stream_0";
            while (CvWorker.IsOnline())
            {
                if(!CvWorker.IsWorking())
                {
                    Thread.Sleep(5000);
                    continue;
                }
                if (CvWorker.GetPlayOption()==3)
                {
                    //Todo

                    continue;
                }
                if (CvWorker.GetPlayOption()==0)
                {
                    if (!capture.Open(0))
                    {
                        CvWorker.SwitchVideo(1, false);
                    }
                }
                else if (CvWorker.GetPlayOption() == 1)
                {
                    if (!capture.Open(rtspUrl))
                    {
                        CvWorker.SwitchVideo(0, false);
                    }
                }
                int oh = capture.FrameHeight;
                int ow = capture.FrameWidth;
                if (ow <= 0 || oh <= 0) continue;
                Size dsize = new Size(400, 400 * oh / ow);
                using (Mat image = new Mat()) // Frame image buffer
                {
                    while (CvWorker.IsWorking())
                    {
                        if (CvWorker.HasChangeRequest())
                        {
                            CvWorker.FinishSwitch();
                            break;
                        }
                        capture.Read(image); // same as cvQueryFrame
                        if (image.Empty()) break;
                        Mat dst = new Mat();
                        Cv2.Resize(image, dst, dsize, 0, 0, InterpolationFlags.Linear);
                        byte[] ByteData = dst.ToBytes(".jpg");
                        var base64StringResult = Convert.ToBase64String(ByteData);
                        await _hubContext.Clients.All.SendAsync("ImagePlay", base64StringResult);
                        Cv2.WaitKey(30);
                    }
                }
                Thread.Sleep(1000);
            }
            await _hubContext.Clients.All.SendAsync("Closed", "Server closed");
          
        }

        
    }
}
